from typing import Callable, Optional
from sqlalchemy.orm import Session
import uuid
from sqlalchemy.future import select
from sqlalchemy import delete
from ...models import Project, ProjectDBModel, StateDBModel


class ProjectCore:
    def __init__(self, make_session: Callable[[], Session]):
        self.session = make_session

    async def get_descriptor(self, token: str) -> Optional[Project]:
        session = self.session()
        with session.begin():
            db_entry = session.query(ProjectDBModel).filter(
                ProjectDBModel.token == token
            ).first()
            if db_entry is None:
                return db_entry
        return Project.model_validate(db_entry)

    async def make(self) -> Optional[Project]:
        new_token = str(uuid.uuid4())
        project = ProjectDBModel(token=new_token)
        session = self.session()
        with session.begin():
            session.add(project)
            session.commit()
        return Project(token=new_token)

    async def delete(self, project: ProjectDBModel) -> bool:
        session = self.session()
        with self.session().begin():
            session.execute(delete(ProjectDBModel).where(
                ProjectDBModel.token == project.token
            ))
            session.commit()
        return True
